package cn.edu.tju.wallet.service;

import cn.edu.tju.wallet.domain.OverdraftRule;
import cn.edu.tju.wallet.domain.OverdraftRule.RuleStatus;
import cn.edu.tju.wallet.dto.OverdraftRuleDTO;
import cn.edu.tju.wallet.repository.OverdraftRuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OverdraftRuleService {

    @Autowired
    private OverdraftRuleRepository overdraftRuleRepository;

    /**
     * 创建透支规则（参考充值规则示例）
     */
    @Transactional
    public OverdraftRule createOverdraftRule(OverdraftRuleDTO dto) {
        OverdraftRule rule = new OverdraftRule();
        rule.setName(dto.getName());
        rule.setMinVipLevel(dto.getMinVipLevel());
        rule.setOverdraftLimit(dto.getOverdraftLimit());
        rule.setDailyInterestRate(dto.getDailyInterestRate());
        rule.setGracePeriodDays(dto.getGracePeriodDays());
        rule.setStatus(RuleStatus.ACTIVE);
        return overdraftRuleRepository.save(rule);
    }

    /**
     * 更新透支规则（参考充值规则示例）
     */
    @Transactional
    public OverdraftRule updateOverdraftRule(Long id, OverdraftRuleDTO dto) {
        OverdraftRule rule = overdraftRuleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("规则不存在"));
        // 更新字段
        rule.setName(dto.getName());
        rule.setMinVipLevel(dto.getMinVipLevel());
        rule.setOverdraftLimit(dto.getOverdraftLimit());
        rule.setDailyInterestRate(dto.getDailyInterestRate());
        rule.setGracePeriodDays(dto.getGracePeriodDays());
        return overdraftRuleRepository.save(rule);
    }

    /**
     * 删除透支规则（参考充值规则示例）
     */
    @Transactional
    public void deleteOverdraftRule(Long id) {
        overdraftRuleRepository.deleteById(id);
    }

    /**
     * 查询所有透支规则（参考充值规则示例）
     */
    public List<OverdraftRule> getAllRules() {
        return overdraftRuleRepository.findAll();
    }
}